class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> ans = new ArrayList<>();

        if(root == null) {
            return ans;
        }

        Queue<TreeNode> queue = new LinkedList<>();
        int n = 0, tail = 0;
        queue.offer(root);
        while(!queue.isEmpty()) {
            TreeNode current = queue.poll();
            tail = current.val;

            if(current.left != null) {
                n++;
                queue.offer(current.left);
            }

            if(current.right != null) {
                n++;
                queue.offer(current.right);
            }

            //能拿到队列长度
            if(n == queue.size() && queue.size() != 0) {
                ans.add(tail);
                n = 0;
            }

            if(queue.size() == 0) {
                ans.add(tail);
            }
        }

        return ans;
    }
}